# 管理员后端接口 admin.py
from functools import wraps
from flask import *
from sqlalchemy import or_
from bluePrints.forms import *
from werkzeug.datastructures import MultiDict
from flask import jsonify, request, session
from werkzeug.datastructures import MultiDict
from exts import *
from models import *
import json,ast

admin = Blueprint('admin',__name__,url_prefix='/admin')

# 默认返回
@admin.route('/')
def admin_index():
    return "管理页面"

# 管理员登录 密码是admin
@admin.route('/admin_login',methods=['POST','GET'])
def admin_login():
    if request.method == 'POST':
        try:
            form = PostLoginAdminForm(MultiDict(request.get_json()))
            print("PostLoginAdminForm:",form.data)
            if form.validate():
                username = form.username.data
                password = form.password.data
                session.permanent = True 
                session[username] = password
                return jsonify({
                    'code':200,
                    'msg':'登录成功',
                    'reply_id': username
                })
            else:
                errors = {field: error[0] for field, error in form.errors.items()}
                print('errors',errors)
                return jsonify({'code': 400, 'errors': errors})
        except Exception as e:
            print('错误',e)
            return jsonify({
                "code": 500,
                "message": f"获取列表数据失败: {str(e)}",
                "data": None
            })
    else:
        return '管理员登录'


# 管理员验证装饰器
def admin_required(func):
    @wraps(func)  # 使用 functools.wraps 保留原函数的元数据
    def decorated_function(*args, **kwargs):
        if 'admin' not in session:  # 检查 session 中是否有 'admin' 键
            return jsonify({
                'code': 401,
                'msg': '未登录或登录已过期，请重新登录'
            }), 401
        elif session['admin'] != 'admin':  # 检查 'admin' 键的值是否为 'admin'
            return jsonify({
                'code': 403,
                'msg': '权限不足，您不是管理员'
            }), 403
        return func(*args, **kwargs)  # 如果验证通过，调用原函数
    return decorated_function

# 获取统计数据
@admin.route('/stats', methods=['GET'])
@admin_required
def get_stats():
    try:
        # 获取各个模型的数量统计
        user_count = User.query.count()
        pet_count = animal.query.count()
        article_count = articles.query.count()
        post_count = Tiezi.query.count()

        # 返回统计数据
        stats = {
            'userCount': user_count,
            'petCount': pet_count,
            'articleCount': article_count,
            'postCount': post_count
        }
        return jsonify({
            'code': 200,
            'message': '获取统计数据成功',
            'data': stats
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取统计数据失败: {str(e)}'
        })



# 获取所有文章分类
@admin.route('/categories', methods=['GET'])
@admin_required
def get_categories():
    try:
        categories = db.session.query(articles.column).distinct().all()
        categories_list = [category[0] for category in categories]
        return jsonify({
            'code': 200,
            'message': '获取分类信息成功',
            'data': categories_list
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取分类信息失败: {str(e)}'
        })






# 获取文章列表
@admin.route('/articles', methods=['GET'])
@admin_required
def get_articles():
    try:
        tag = request.args.get('tag', '全部')
        search_title = request.args.get('search_title', '')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        page = int(request.args.get('page', 1))
        per_page = 20

        query = articles.query

        if tag != '全部':
            query = query.filter(articles.column == tag)

        if search_title:
            query = query.filter(articles.title.contains(search_title))

        if start_date:
            query = query.filter(articles.view_date >= start_date)

        if end_date:
            query = query.filter(articles.view_date <= end_date)

        paginated_articles = query.paginate(page=page, per_page=per_page, error_out=False)
        articles_data = [
            {
                'id': article.id,
                'title': article.title,
                'view_date': article.view_date.strftime('%Y-%m-%d %H:%M:%S') if article.view_date else None,
                'contents_json': contentUcode(article.contents_json),  # 确保返回的是JSON字符串
                'column': article.column
            }
            for article in paginated_articles.items

        ]
        return jsonify({
            'code': 200,
            'message': '获取文章列表成功',
            'data': articles_data,
            'total': paginated_articles.total
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取文章列表失败: {str(e)}'
        })



# 添加文章
@admin.route('/articles', methods=['POST'])
@admin_required
def add_article():
    try:
        data = request.get_json()
        print('contents_json',contentUcode(data['contents_json']))
        # 创建表单对象并验证数据
        form = ArticleForm(data=data)
        if not form.validate():
            errors = {field: errors[0] for field, errors in form.errors.items()}
            return jsonify({
                'code': 400,
                'message': '数据验证失败',
                'errors': errors
            }), 400
        
        # 使用 form.data 获取所有验证后的数据
        form_data = form.data
        # 打印验证后的数据
        print('验证后的数据:', form_data)
        
        # 创建新文章对象
        new_article = articles(
            title=form_data['title'],
            view_date=form_data['view_date'],
            contents_json=json.dumps(contentUcode(data['contents_json'])),
            column=form_data['column']
        )
        print('new_article',new_article)
        
        # 保存到数据库
        db.session.add(new_article)
        db.session.commit()
        
        # 返回成功响应
        return jsonify({
            'code': 200,
            'message': '添加文章成功',
            'data': {
                'id': new_article.id,
                'title': new_article.title,
                'view_date': new_article.view_date.strftime('%Y-%m-%d %H:%M:%S'),
                'contents_json': new_article.contents_json,
                'column': new_article.column
            }
        })
    except Exception as e:
        db.session.rollback()
        print('添加文章失败:', str(e))
        return jsonify({
            'code': 500,
            'message': f'添加文章失败: {str(e)}'
        }), 500
    

# 更新文章
@admin.route('/articles/<int:article_id>', methods=['PUT'])
@admin_required
def update_article(article_id):
    try:
        data = request.get_json()
        # print(data)
        article = articles.query.get(article_id)
        if not article:
            return jsonify({'code': 404, 'message': '文章未找到'})
        article.title = data.get('title')
        article.view_date = data.get('view_date')
        article.contents_json = str(json.dumps(data.get('contents_json')))
        article.column = data.get('column')
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': '更新文章成功',
            'data': {
                'id': article.id,
                'title': article.title,
                'view_date': article.view_date.strftime('%Y-%m-%d %H:%M:%S') if article.view_date else None,
                'contents_json': article.contents_json,
                'column': article.column
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'更新文章失败: {str(e)}'
        })

 
# 删除文章api
@admin.route('/articles/<int:article_id>', methods=['DELETE'])
@admin_required
def delete_article(article_id):
    try:
        article = articles.query.get(article_id)
        if not article:
            return jsonify({
                'code': 404,
                'message': '文章未找到'
            })
        
        # 在删除前归档文章数据
        Archive.add_archive(
            original_id=article.id,
            data_type='article',
            data_content=article.to_dict(),
            reason='管理员删除'
        )
        
        db.session.delete(article)
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': '删除文章成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'删除文章失败: {str(e)}'
        })

# 获取宠物分类
@admin.route('/pet_categories', methods=['GET'])
@admin_required
def get_pet_categories():
    try:
        categories = animal.get_all_pet_categories()
        return jsonify({
            'code': 200,
            'message': '获取宠物分类成功',
            'data': categories
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取宠物分类失败: {str(e)}'
        })

# 获取宠物列表
@admin.route('/pets', methods=['GET'])
@admin_required
def get_pets():
    try:
        # 获取请求参数
        category = request.args.get('category', None)  # 宠物分类
        name = request.args.get('name', '')  # 获取名称搜索参数
        page = int(request.args.get('page', 1))  # 当前页码，默认为第 1 页
        per_page = 20  # 每页显示的宠物数量

        query = animal.query

        # 根据宠物分类筛选
        if category and category != '全部':
            query = query.filter(animal.分类 == category)

        # 根据名称搜索（同时搜索全名和别名）
        if name:
            query = query.filter(or_(
                animal.全名.contains(name),
                animal.别名.contains(name)
            ))

        # 分页查询
        paginated_pets = query.paginate(page=page, per_page=per_page, error_out=False)

        if not paginated_pets.items:
            return jsonify({
                'code': 404,
                'message': '未找到符合条件的宠物',
                'data': [],
                'total': 0,
                'pages': 0,
                'current_page': page
            })

        pets_data = [
            {
                'id': pet.id,
                '全名': pet.全名,
                '别名': pet.别名,
                '分类': pet.分类,
                '体型': pet.体型,
                '毛发': pet.毛发,
                '智商': pet.智商,
                '寿命': pet.寿命,
                '饲养': pet.饲养,
                '功能': pet.功能,
                '原产地': pet.原产地,
                '价格': pet.价格,
                'imgPath': pet.imgPath,
                '简介': pet.简介,
            }
            for pet in paginated_pets.items
        ]

        return jsonify({
            'code': 200,
            'message': '获取宠物列表成功',
            'data': pets_data,
            'total': paginated_pets.total,  # 总宠物数量
            'pages': paginated_pets.pages,  # 总页数
            'current_page': paginated_pets.page  # 当前页码
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取宠物列表失败: {str(e)}'
        })

# 添加宠物
@admin.route('/pets', methods=['POST'])
@admin_required
def add_pet():
    try:
        form=PetForm(MultiDict(request.get_json()))
        print('form', form.data)
        if not form.validate():
            # 返回具体的验证错误信息
            errors = {field: errors[0] for field, errors in form.errors.items()}
            return jsonify({
                'code': 400,
                'message': '数据验证失败',
                'errors': errors
            }), 400
        
        form_data = form.data
        new_pet = animal(
            全名=form_data['全名'],
            别名=form_data['别名'],
            分类=form_data['分类'],
            体型=form_data['体型'],
            毛发=form_data['毛发'],
            智商=form_data['智商'],
            寿命=form_data['寿命'],
            饲养=form_data['饲养'],
            功能=form_data['功能'],
            原产地=form_data['原产地'],
            价格=form_data['价格'],
            imgPath=form_data['imgPath'],
            简介=form_data['简介'],
        )
        
        db.session.add(new_pet)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '添加宠物成功',
            'data': {
                'id': new_pet.id,
                '全名': new_pet.全名,
                '别名': new_pet.别名,
                '分类': new_pet.分类,
                '体型': new_pet.体型,
                '毛发': new_pet.毛发,
                '智商': new_pet.智商,
                '寿命': new_pet.寿命,
                '饲养': new_pet.饲养,
                '功能': new_pet.功能,
                '原产地': new_pet.原产地,
                '价格': new_pet.价格,
                'imgPath': new_pet.imgPath,
                '简介': new_pet.简介,
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'添加宠物失败: {str(e)}'
        }), 500

# 更新宠物信息
@admin.route('/pets/<int:pet_id>', methods=['PUT'])
@admin_required
def update_pet(pet_id):
    try:
        form=PetForm(MultiDict(request.get_json()))
        pet = animal.query.get(pet_id)
        if not pet:
            return jsonify({'code': 404, 'message': '宠物未找到'})
        
        if not form.validate():
            errors = {field: errors[0] for field, errors in form.errors.items()}
            return jsonify({
                'code': 400,
                'message': '数据验证失败',
                'errors': errors
            }), 400
        
        form_data = form.data
        pet.全名 = form_data['全名']
        pet.别名 = form_data['别名']
        pet.分类 = form_data['分类']
        pet.体型 = form_data['体型']
        pet.毛发 = form_data['毛发']
        pet.智商 = form_data['智商']
        pet.寿命 = form_data['寿命']
        pet.饲养 = form_data['饲养']
        pet.功能 = form_data['功能']
        pet.原产地 = form_data['原产地']
        pet.价格 = form_data['价格']
        pet.imgPath = form_data['imgPath']
        pet.简介 = form_data['简介']
        
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': '更新宠物信息成功',
            'data': {
                'id': pet.id,
                '全名': pet.全名,
                '别名': pet.别名,
                '分类': pet.分类,
                '体型': pet.体型,
                '毛发': pet.毛发,
                '智商': pet.智商,
                '寿命': pet.寿命,
                '饲养': pet.饲养,
                '功能': pet.功能,
                '原产地': pet.原产地,
                '价格': pet.价格,
                'imgPath': pet.imgPath,
                '简介': pet.简介,
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'更新宠物信息失败: {str(e)}'
        })

# 删除宠物
@admin.route('/pets/<int:pet_id>', methods=['DELETE'])
@admin_required
def delete_pet(pet_id):
    try:
        pet = animal.query.get(pet_id)
        if not pet:
            return jsonify({
                'code': 404,
                'message': '未找到指定宠物'
            })
        
        # 在删除前归档宠物数据
        Archive.add_archive(
            original_id=pet.id,
            data_type='pet',
            data_content=pet.to_dict(),
            reason='管理员删除'
        )
        
        db.session.delete(pet)
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': '宠物删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'删除宠物失败: {str(e)}'
        })


# 获取帖子列表
@admin.route('/tiezis', methods=['GET'])
@admin_required
def get_tiezis():
    try:
        search_title = request.args.get('search_title', '')
        search_content = request.args.get('search_content', '')
        page = int(request.args.get('page', 1))
        per_page = 20

        query = Tiezi.query.join(User, Tiezi.user_id == User.id)

        if search_title:
            query = query.filter(Tiezi.title.contains(search_title))
        
        if search_content:
            query = query.filter(Tiezi.content.contains(search_content))

        paginated_tiezis = query.paginate(page=page, per_page=per_page, error_out=False)
        
        tiezis_data = [
            {
                'id': tiezi.id,
                'title': tiezi.title,
                'content': tiezi.content,
                'create_time': tiezi.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'user_id': tiezi.user_id,
                'username': User.query.get(tiezi.user_id).username,
                'like_num': tiezi.like_num,
                'reply_count': Reply.query.filter_by(post_id=tiezi.id).count()
            }
            for tiezi in paginated_tiezis.items
        ]
        
        return jsonify({
            'code': 200,
            'message': '获取帖子列表成功',
            'data': tiezis_data,
            'total': paginated_tiezis.total
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取帖子列表失败: {str(e)}'
        })

# 获取帖子详情
@admin.route('/tiezis/<int:tiezi_id>', methods=['GET'])
@admin_required
def get_tiezi_detail(tiezi_id):
    try:
        tiezi = Tiezi.query.get(tiezi_id)
        if not tiezi:
            return jsonify({
                'code': 404,
                'message': '帖子未找到'
            })
        
        user = User.query.get(tiezi.user_id)
        
        tiezi_data = {
            'id': tiezi.id,
            'title': tiezi.title,
            'content': tiezi.content,
            'create_time': tiezi.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'user_id': tiezi.user_id,
            'username': user.username if user else '未知用户',
            'like_num': tiezi.like_num,
            'reply_count': Reply.query.filter_by(post_id=tiezi.id).count()
        }
        
        return jsonify({
            'code': 200,
            'message': '获取帖子详情成功',
            'data': tiezi_data
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取帖子详情失败: {str(e)}'
        })

# 更新帖子
@admin.route('/tiezis/<int:tiezi_id>', methods=['PUT'])
@admin_required
def update_tiezi(tiezi_id):
    try:
        data = request.get_json()
        tiezi = Tiezi.query.get(tiezi_id)
        if not tiezi:
            return jsonify({
                'code': 404,
                'message': '帖子未找到'
            })
        
        # 更新帖子信息
        if 'title' in data:
            tiezi.title = data['title']
        if 'content' in data:
            tiezi.content = data['content']
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新帖子成功',
            'data': {
                'id': tiezi.id,
                'title': tiezi.title,
                'content': tiezi.content,
                'create_time': tiezi.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'user_id': tiezi.user_id,
                'like_num': tiezi.like_num
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'更新帖子失败: {str(e)}'
        })

# 删除帖子
@admin.route('/tiezis/<int:tiezi_id>', methods=['DELETE'])
@admin_required
def delete_tiezi(tiezi_id):
    try:
        tiezi = Tiezi.query.get(tiezi_id)
        if not tiezi:
            return jsonify({
                'code': 404,
                'message': '帖子未找到'
            })
        
        # 在删除前归档帖子数据
        Archive.add_archive(
            original_id=tiezi.id,
            data_type='post',
            data_content=tiezi.to_dict(),
            reason='管理员删除'
        )
        
        # 先删除与帖子相关的所有回复
        Reply.query.filter_by(post_id=tiezi_id).delete()
        
        # 然后删除帖子
        db.session.delete(tiezi)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '删除帖子成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'删除帖子失败: {str(e)}'
        })
    


# 获取用户列表
@admin.route('/users', methods=['GET'])
@admin_required
def get_users():
    try:
        search = request.args.get('search', '')
        page = int(request.args.get('page', 1))
        per_page = 20

        query = User.query
        if search:
            query = query.filter(User.username.contains(search))

        paginated_users = query.paginate(page=page, per_page=per_page, error_out=False)
        users_data = [
            {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'password': user.password,
                'register_time': user.register_time.strftime('%Y-%m-%d %H:%M:%S') if user.register_time else None,
                'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None,
                'post_count': Tiezi.query.filter_by(user_id=user.id).count()
            }
            for user in paginated_users.items
        ]

        return jsonify({
            'code': 200,
            'message': '获取用户列表成功',
            'data': users_data,
            'total': paginated_users.total
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取用户列表失败: {str(e)}'
        })

# 添加用户
@admin.route('/users', methods=['POST'])
@admin_required
def add_user():
    try:
        form = UserForm(MultiDict(request.get_json()))
        if not form.validate():
            errors = {field: errors[0] for field, errors in form.errors.items()}
            return jsonify({
                'code': 400,
                'message': '数据验证失败',
                'errors': errors
            }), 400

        new_user = User(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data
        )
        new_user.set_password(form.password.data)
        
        db.session.add(new_user)
        db.session.commit()

        return jsonify({
            'code': 200,
            'message': '添加用户成功',
            'data': {
                'id': new_user.id,
                'username': new_user.username,
                'email': new_user.email
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'添加用户失败: {str(e)}'
        })

# 更新用户
@admin.route('/users/<int:user_id>', methods=['PUT'])
@admin_required
def update_user(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'code': 404,
                'message': '用户不存在'
            })

        form = UserUpdateForm(MultiDict(request.get_json()))
        form.user_id = user_id
        
        if not form.validate():
            errors = {field: errors[0] for field, errors in form.errors.items()}
            return jsonify({
                'code': 400,
                'message': '数据验证失败',
                'errors': errors
            }), 400

        user.username = form.username.data
        user.email = form.email.data
        if form.password.data:  # 如果提供了新密码
            user.set_password(form.password.data)

        db.session.commit()
        return jsonify({
            'code': 200,
            'message': '更新用户成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'更新用户失败: {str(e)}'
        })

# 删除用户
@admin.route('/users/<int:user_id>', methods=['DELETE'])
@admin_required
def delete_user(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'code': 404,
                'message': '用户不存在'
            })

        # 在删除前归档用户数据
        Archive.add_archive(
            original_id=user.id,
            data_type='user',
            data_content=user.to_dict(),
            reason='管理员删除'
        )

        # 删除用户相关的所有数据
        Reply.query.filter_by(user_id=user_id).delete()
        Tiezi.query.filter_by(user_id=user_id).delete()
        db.session.delete(user)
        db.session.commit()

        return jsonify({
            'code': 200,
            'message': '删除用户成功',
            'data':None
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'删除用户失败: {str(e)}',
            'data':None
        })




# 获取归档列表
@admin.route('/archives', methods=['GET'])
@admin_required
def get_archives():
    try:
        # 获取查询参数
        archive_type = request.args.get('type', '')
        keyword = request.args.get('keyword', '')
        page = int(request.args.get('page', 1))
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        per_page = int(request.args.get('per_page', 10))

        # 构建基础查询
        query = Archive.query

        # 类型过滤
        if archive_type:
            query = query.filter(Archive.type == archive_type)

        # 关键字搜索（标题或内容）
        if keyword:
            query = query.filter(or_(
                Archive.title.ilike(f'%{keyword}%'),
                Archive.content.ilike(f'%{keyword}%')
            ))

        # 日期范围过滤
        if start_date and end_date:
            start = datetime.strptime(f"{start_date} 00:00:00", '%Y-%m-%d %H:%M:%S')
            end = datetime.strptime(f"{end_date} 23:59:59", '%Y-%m-%d %H:%M:%S')
            query = query.filter(Archive.deleted_at.between(start, end))

        # 按删除时间倒序排序
        query = query.order_by(Archive.deleted_at.desc())

        # 分页查询
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        # 格式化返回数据
        archives = [{
            'id': item.id,
            'type': item.type,
            'title': item.title,
            'content': json.loads(item.content) if item.content else None,
            'deleted_at': item.deleted_at.strftime('%Y-%m-%d %H:%M:%S') if item.deleted_at else None,
            'original_id': item.original_id,
            'reason': item.reason
        } for item in pagination.items]

        return jsonify({
            'code': 200,
            'message': '获取回收站数据成功',
            'data': {
                'items': archives,
                'total': pagination.total,
                'current_page': page,
                'per_page': per_page
            }
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取回收站数据失败: {str(e)}'
        })

# 恢复归档数据
@admin.route('/archives/<int:id>/restore', methods=['POST'])
@admin_required  # 添加管理员权限验证
def restore_archive(id):
    try:
        archive = Archive.query.get_or_404(id)
        content = json.loads(archive.content)
        
        # 根据不同类型恢复数据
        if archive.type == 'user':
            # 修复用户密码处理逻辑
            new_user = User(**content)
            db.session.add(new_user)
        elif archive.type == 'pet':
            new_pet = animal(**content)
            db.session.add(new_pet)
        elif archive.type == 'article':
            new_article = articles(**content)
            db.session.add(new_article)
        elif archive.type == 'post':
            new_post = Tiezi(**content)
            db.session.add(new_post)
        else:
            return jsonify({
                'code': 400,
                'message': f'不支持的数据类型: {archive.type}'
            })

        # 删除归档记录
        db.session.delete(archive)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '数据恢复成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'数据恢复失败: {str(e)}'
        })

# 彻底删除归档数据
@admin.route('/archives/<int:id>/permanent', methods=['DELETE'])
@admin_required  # 添加管理员权限验证
def delete_permanent(id):
    try:
        archive = Archive.query.get_or_404(id)
        
        # 删除归档记录
        db.session.delete(archive)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '数据已彻底删除'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'彻底删除失败: {str(e)}'
        })




# 解码contents_json
def contentUcode(contents_json):
    try:
        contents_json = contents_json
        # 如果已经是列表，直接返回
        if isinstance(contents_json, list):
            # print('list',contents_json)
            return contents_json
        # 如果是字符串，则解码
        elif isinstance(contents_json, str):
            # print('str',contents_json)
            return json.loads(contents_json)
            # return json.dumps(ast.literal_eval(contents_json),ensure_ascii=False)
        # 其他情况返回None
        return None
    except json.JSONDecodeError as e:
        print('json解码错误', e)
        return None